package com.example.backed.service.impl;

import com.example.backed.dto.AuthResponse;
import com.example.backed.dto.LoginRequest;
import com.example.backed.dto.RegisterRequest;
import com.example.backed.entity.User;
import com.example.backed.mapper.UserMapper;
import com.example.backed.service.AuthService;
import com.example.backed.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;

@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

    private final AuthenticationManager authenticationManager;
    private final JwtUtil jwtUtil;
    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;

    // 默认用户角色ID（假设数据库中已存在该角色）
    private static final Long DEFAULT_ROLE_ID = 2L;

    @Override
    public AuthResponse login(LoginRequest request) {
        try {
            System.out.println("登录请求: " + request.getUsername());
            
            // 进行身份认证
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword())
            );

            // 获取认证后的用户信息
            User user = (User) authentication.getPrincipal();
            System.out.println("认证成功，用户: " + user.getUsername());

            // 生成JWT令牌
            String token = jwtUtil.generateToken(user);
            System.out.println("生成的token: " + token);

            // 获取用户角色
            String[] roles = user.getAuthorities().stream()
                    .map(GrantedAuthority::getAuthority)
                    .map(role -> role.replace("ROLE_", ""))
                    .toArray(String[]::new);
            System.out.println("用户角色: " + String.join(", ", roles));

            // 返回认证响应
            return new AuthResponse(token, user.getUsername(), user.getNickname(), roles);
        } catch (Exception e) {
            System.err.println("登录失败: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    @Transactional
    public AuthResponse register(RegisterRequest request) {
        try {
            // 检查用户名是否已存在
            if (userMapper.findByUsername(request.getUsername()) != null) {
                throw new RuntimeException("用户名已存在");
            }

            // 创建用户实体
            User user = new User();
            user.setUsername(request.getUsername());
            user.setPassword(passwordEncoder.encode(request.getPassword()));
            user.setNickname(request.getNickname());
            user.setPhone(request.getPhone());
            user.setEmail(request.getEmail());
            user.setAvatar("https://example.com/default-avatar.png"); // 设置默认头像
            user.setStatus(1); // 1-启用
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            user.setRoles(new ArrayList<>()); // 初始化角色列表

            // 保存用户信息
            int result = userMapper.insert(user);
            if (result <= 0) {
                throw new RuntimeException("用户信息保存失败");
            }

            // 分配默认角色
            result = userMapper.insertUserRole(user.getId(), DEFAULT_ROLE_ID);
            if (result <= 0) {
                throw new RuntimeException("用户角色分配失败");
            }

            // 直接返回成功响应，不尝试登录
            return new AuthResponse(null, user.getUsername(), user.getNickname(), new String[]{"USER"});
        } catch (Exception e) {
            // 记录详细错误信息
            e.printStackTrace();
            throw new RuntimeException("注册失败: " + e.getMessage(), e);
        }
    }
} 